package cn.maidouya.hrm.service;

import cn.maidouya.hrm.domain.LoginUser;
import cn.maidouya.hrm.domain.Permission;
import cn.maidouya.hrm.mapper.LongUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *   1. 导入 阿里巴巴druid线程池 mybat-plus security
 *   2. 配置文件 端口 database 别名
 *   3. config配置
 *          @Configuration
             @EnableWebSecurity
             配置编码器
             授权规则配置
        4. domain实体类
        5. 查询数据封装
        6. controller接收UserDetailservice回调地址

 */
@Service // 注解注入交给spring管理
public class MyUserDetaillServiceImpl implements UserDetailsService {
    @Autowired // 注解方式动态获取方法
    private LongUserMapper longUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询username在数据库中是否存在
        LoginUser longUser = longUserMapper.loadUserByUsername(username);
        // 2. username为空的话就抛出异常
        if (longUser ==  null){
            throw new RuntimeException("用户不存在！");
        }
        // 3. 创建ArrayList集合泛型为SimpleGrantedAuthority保存permission对象  security提供SimpleGrantedAuthority的泛型
        ArrayList<SimpleGrantedAuthority> authors = new ArrayList<SimpleGrantedAuthority>();
        // 4. 根据id查询自己所在的授权权限
        List<Permission> permissions = longUserMapper.getByIdPermission(longUser.getId());
        //System.out.println("用户个人权限：" +permissions);

        // 5. permission资源权限遍历
            permissions.stream().forEach(permission -> {
        // 6. 创建 authority 保存每个用户权限 与security中拦截器对比，如果对比一致则放行   不一致拦截
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
                System.out.println("个人权限" +permission.getSn());
                authors.add(authority);
            });
        // 7. security框架提供User保存对象数据给interceptor管理
            User user = new User(longUser.getUsername(), longUser.getPassword(), authors);

        return user;
    }

    public static void main(String[] args) {
        // BCryptPasswordEncoder加密方法，解密方法
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode("2");
        System.out.println(encode);
    }
}